/**
 * COPYRIGHT. Harry Wu 2011. ALL RIGHTS RESERVED.
 * Project: just
 * Author: Harry Wu <harrywu304@gmail.com>
 * Created On: Jun 16, 2011 2:25:36 PM
 *
*/ 
package org.justframework.core;

import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

/**
 * Handle request and return response
 *
 */
public class RequestHandler {
	
	/**
	 * handler request and return response
	 * @param request
	 * @param context
	 * @return
	 */
	public Response handle(Request request, Map context){
		Response response = null;
		
		//locate resource
		Map<String,String> urlParams = new HashMap<String,String>();
		Class klass = RequestRouter.locate(request.getUri().getPath(),urlParams);
		request.getOptions().put("urlParams",urlParams);
		
		//invoke corresponding method
		if(klass != null){
			try{
				String requestMethod = request.getRequestMethod().toString().toLowerCase();
				Method method = klass.getMethod(requestMethod, Request.class);
				if(method != null){
					response = (Response)method.invoke(klass.newInstance(), request);
				} 
			}catch(Exception e){
				e.printStackTrace();
			}
		}
		return response;
	}

}
